const fs = require('fs');
const path = require('path')

const resourceConfigFileName = 'resource.json';

const localDirs = [
    './bin/config',
    './bin/Resource',
    './bin/res'
];

const cdnDir = '../ClientAssets';
// const cdnDir = '';

let jsonData = [];
let imageData = [];
let atlasData = [];

let config = {};

// TODO: 找不到的文件夹还会报错，需要自行注释掉
main();

function main() {
    for (const dir of localDirs) {
        scan(resolvePath(dir))
    }
    
    config['local'] =  buildConfig(resolvePath('./bin/'));
    clearTempData();

    if (cdnDir) {
        scan(cdnDir);
        config['cdn'] = buildConfig(resolvePath(cdnDir));        
    }

    writeConfig(config);
    console.log('resource config build finish ....\n');
}


function scan(rootDir) {
    if (!fs.existsSync(rootDir)) {
        return;
    }
    let dirChildren = fs.readdirSync(rootDir);

    // atlas, must first
    let atlas = dirChildren
        .filter(fileName => isAtlas(fileName))
        .map(fileName => getFullPath(rootDir, fileName));
    atlasData = atlasData.concat(atlas);

    // json
    let jsons = dirChildren
        .filter(fileName => isJson(fileName))
        .map(fileName => getFullPath(rootDir, fileName))
        .filter(json => !json.endsWith(resourceConfigFileName));
    jsonData = jsonData.concat(jsons);

    // image 
    let images = dirChildren
        .filter(fileName => isImage(fileName) && !isAtlasImage(getFullPath(rootDir, fileName)))
        .map(fileName => getFullPath(rootDir, fileName))
    imageData = imageData.concat(images);

    // subdirs
    let subDirs = dirChildren.filter(fileName => isDirectory(getFullPath(rootDir, fileName)));
    for (const subDir of subDirs) {
        scan(getFullPath(rootDir, subDir));
    }
}


function isJson(fileName) {
    return fileName.endsWith('.json');
}

function isAtlas(fileName) {
    return fileName.endsWith('.atlas');
}

function isImage(fileName) {
    let imgExts = [
        '.jpg',
        '.png',
        '.jpeg'
    ];
    return imgExts.some(imgExt => fileName.endsWith(imgExt));
}

function isAtlasImage(image) {
    return atlasData.some(item => {
        return item.replace('.atlas', '') === image.replace(/[1-9]?\.\w+$/, '');
    });
}

function resolvePath(relativePath) {
    return path.resolve(relativePath);
}

function getFullPath(basePath, fileName) {
    return path.join(basePath, fileName);
}

function isDirectory(path) {
    return fs.statSync(path).isDirectory()
}

function buildConfig(basePath) {
    let configData = [];
    configData.push({
        type: 'json',
        urls: jsonData.map(jsonItem => getResourceUrl(basePath, jsonItem))
    });
    configData.push({
        type: 'atlas',
        urls: atlasData.map(atlasItem => getResourceUrl(basePath, atlasItem))
    });
    configData.push({
        type: 'image',
        urls: imageData.map(imageItem => getResourceUrl(basePath, imageItem))
    });

    return configData;
}

function getResourceUrl(basePath, resourcePath) {
    if (!basePath.endsWith('\\')) {
        basePath = basePath + '\\';
    }
    return resourcePath.replace(basePath, '')
        .split(path.sep)
        .join('/');        
}

function clearTempData() {
    jsonData = [];
    imageData = [];
    atlasData = [];
}

function writeConfig(config) {
    let jsonStr = JSON.stringify(config, null, 4);
    fs.writeFileSync(path.join('./bin/config', resourceConfigFileName), jsonStr);    
}